<template>
  <div v-if="h5">1</div>
  <widget-form-item v-else :designer="designer" :widget-list="widgetList" :item="item" :index="index">
    <el-scrollbar>
      <div class="ep-subform-table">
        <div v-for="(cell, i) in item.options.formItems" :key="i" class="ep-subform-table-box" style="width: 180px">
          <div class="ep-subform-table-cell header">
            <div class="cell">{{ cell.options.label }}</div>
          </div>
          <div v-for="(value, k) in fieldModel" :key="k" class="ep-subform-table-cell">
            <div class="cell">
              <component
                :is="`m-${cell.type}`"
                v-model="value[cell.options.name]"
                :form-data="value"
                :widget-list="item.options.formItems"
                :item="getCell(cell)"
                :index="k"
                :detail="false"
              />
            </div>
          </div>
        </div>
      </div>
    </el-scrollbar>
  </widget-form-item>
</template>

<script>
import { reactive, toRefs, computed } from 'vue'
import draggable from '@marshallswain/vuedraggable'
import props from './props'

export default {
  name: 'MSubform',
  components: { draggable },
  props,
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    const drag = reactive({
      dragging: false,
      componentData: {
        tag: 'div',
        type: 'transition-group'
      },
      dragOptions: {
        animation: 300,
        group: 'people',
        ghostClass: 'ghost',
        disabled: false,
        handle: '.drag-handler'
      }
    })
    const { dragging, componentData, dragOptions } = toRefs(drag)

    const fieldModel = computed({
      get() {
        return props.modelValue || [{}]
      },
      set(val) {
        if (!props.designer) {
          emit('update:modelValue', val)
        }
      }
    })

    const getCell = (item) => {
      const copyItem = JSON.parse(JSON.stringify(item))
      copyItem.options.label = ''
      return copyItem
    }

    return {
      fieldModel,
      dragging,
      componentData,
      dragOptions,
      getCell
    }
  }
}
</script>

<style lang="less" scoped>
.ep-subform-table {
  display: flex;
  width: fit-content;
  border-left: 1px solid #ebeef5;
  border-top: 1px solid #ebeef5;
  min-width: 100%;

  .ep-subform-table-box {
    display: flex;
    flex-direction: column;
    width: fit-content;

    .ep-subform-table-cell {
      display: flex;
      border-right: 1px solid #ebeef5;
      border-bottom: 1px solid #ebeef5;

      &.header {
        background-color: #f5f7fa;
      }

      .cell {
        box-sizing: border-box;
        padding: 8px 12px;
        line-height: 23px;
        text-overflow: ellipsis;
        white-space: nowrap;
        overflow: hidden;
        overflow-wrap: break-word;
      }
    }
  }
}
</style>
